import os
import shutil

from docx import Document

import DataGrouping
import TableData
import WordHelper
from pathlib import Path


def divideAOTable(doc: Document):
    tableDict = {}
    for table_index, table in enumerate(doc.tables):
        print("table:", type(table))
        tableFound = False
        for row_index, row in enumerate(table.rows):
            if tableFound:
                continue
            for col_index, cell in enumerate(row.cells):
                if tableFound:
                    continue
                clean_text = cell.text.strip()
                if col_index == 0 and row_index == 0:
                    print(f"info -- 第一单元格{clean_text}, table {table_index}")
                if col_index == 0 and row_index == 0 and not clean_text.startswith(WordHelper.kSkpi):
                    if clean_text.startswith(WordHelper.TableE.kModel.value):
                        tableDict[WordHelper.TableE.kModel.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.TableE.kStandNInfo.value):
                        tableDict[WordHelper.TableE.kStandNInfo.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.TableE.kRev.value):
                        tableDict[WordHelper.TableE.kRev.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.TableE.kToolEquip.value):
                        tableDict[WordHelper.TableE.kToolEquip.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.TableE.kPart.value):
                        tableDict[WordHelper.TableE.kPart.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.TableE.kSket.value):
                        tableDict[WordHelper.TableE.kSket.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.TableE.kCatalog.value):
                        tableDict[WordHelper.TableE.kCatalog.value] = table
                        tableFound = True

                elif row_index == 0 and col_index == 4 and clean_text.startswith(WordHelper.TableE.kSeqEg.value):
                    tableDict[WordHelper.TableE.kSeqEg.value] = table
                    tableFound = True

                # elif row_index == 0 and col_index == 5 and clean_text.startswith(TableE.kSeqAA.value):
                #     tableDict[TableE.kSeqAA.value] = table
                #     tableFound = True

        if not tableFound:
            raise ValueError("非在记录表格")
    return tableDict


def process_word_template_ao(configFilePath, groupedData: DataGrouping.GroupData) -> Path:
    print(configFilePath)

    headerData = groupedData.header
    if not isinstance(headerData, TableData.Header):
        raise Exception("读取头部信息失败")

    target_file_name = headerData.no

    source_file_path = configFilePath + '\\F010203-01装配大纲Rev.8.docx'
    copied_file_path = configFilePath + f'\\AO_{target_file_name}.docx'

    # 确保源文件存在
    if not os.path.exists(source_file_path):
        raise FileNotFoundError(f"源文件不存在: {source_file_path}")

    # 复制文件
    shutil.copy2(source_file_path, copied_file_path)

    # 打开文档
    doc = Document(copied_file_path)

    # 获取第一个表格用于写入
    if not doc.tables:
        raise ValueError("文档中没有表格")

    # 页眉表格处理 ===========================================
    print(f"doc.sections 个数为 '{len(doc.sections)}'")
    for section_index, section in enumerate(doc.sections):
        header = section.header

        if header.is_linked_to_previous:
            continue

        for table in header.tables:
            headerItemDict = {}
            for row_index, row in enumerate(table.rows):
                for col_index, cell in enumerate(row.cells):
                    clean_text = cell.text.strip()
                    print(f"Found header table cell: '{clean_text}'")
                    if clean_text == 'AO编号AO NO.' or clean_text == 'AO版次AO REV.' or clean_text == 'AO名称 AO TITLE':
                        headerItemDict[clean_text] = {
                            'cell': cell,
                            'row': row_index,
                            'col': col_index
                        }

            if headerItemDict:
                if headerItemDict['AO编号AO NO.']:
                    cell_info = headerItemDict['AO编号AO NO.']
                    target_col = cell_info['col'] + 1
                    cTxt = headerData.no
                    table.cell(cell_info['row'], target_col).text = f'AO_{cTxt}'
                if headerItemDict['AO版次AO REV.']:
                    cell_info = headerItemDict['AO版次AO REV.']
                    target_col = cell_info['col'] + 1
                    cTxt = headerData.rev
                    table.cell(cell_info['row'], target_col).text = cTxt
                if headerItemDict['AO名称 AO TITLE']:
                    cell_info = headerItemDict['AO名称 AO TITLE']
                    target_col = cell_info['col'] + 1
                    cTxt = headerData.title
                    table.cell(cell_info['row'], target_col).text = cTxt

        break
    # 页眉表格处理结束 ************************************************************

    # 表格分离
    tableInfoDictAO = {}  # TableE --> TableInfo
    tableDictAO = divideAOTable(doc)
    for t in WordHelper.TableE:
        if tableDictAO[t.value]:
            tCellDict, tTableMat = WordHelper.resolveTable(tableDictAO[t.value])
            tableInfoDictAO[t.value] = WordHelper.TableInfo(tableDictAO[t.value], tCellDict, tTableMat)
        else:
            raise Exception(f"缺表{t.value}")

    del tableDictAO

    print()
    print("表格信息 =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*")
    for tName, tInfo in tableInfoDictAO.items():
        print(f"look into table {tName}: ===============")
        cellDict = tInfo.cellDict
        for cTxt, mergedCells in cellDict.items():
            cleaned_text = cTxt.replace('\n', '').replace('\r', '')

            print(f"{cleaned_text}, ====> {mergedCells}")
        print(f"table {tName} done: ******************")
        print()

    print("^^^^^^^^^^^^^^^^^^^^^^^^^def table^^^^^^^^^^^^^^^^^^^^^^^^^")

    # 草图表
    table_sketch = WordHelper.TableSketch(tableInfoDictAO[WordHelper.TableE.kSket.value], WordHelper.TableE.kSket)
    # table_sketch.printCells()
    sketches = groupedData.sketch
    for sketch in sketches.getAll():
        table_sketch.addSketchPic(sketch)

    # 零件表
    table_part = WordHelper.TablePart(tableInfoDictAO[WordHelper.TableE.kPart.value], WordHelper.TableE.kPart)
    # table_part.printCells()
    # table_part.printMatrix()
    parts = groupedData.part
    table_part.addRows(parts.getAll())
    # for part in parts.getAll():
    #     if isinstance(part, TableData.PartRecord):
    #         table_part.addItem(part.seq, part.no, part.name, part.spec, part.typ,
    #                            part.qty, part.nex, part.note)

    # 工序表
    table_aa = WordHelper.TableSeq(tableInfoDictAO[WordHelper.TableE.kSeqEg.value], WordHelper.TableE.kSeqEg)
    # table_aa.printCells()
    # table_aa.printMatrix()
    process = groupedData.process
    tagPath = f'{configFilePath}\\key.png'
    # for p in process.getAll():
    #     if isinstance(p, TableData.ProcessRecord):
    #         table_aa.addItem(p.seq, p.process, p.instructions, p.tooling, p.eg, p.key, tagPath)
    table_aa.addRows(process.getAll(), tagPath)

    # 资源表
    table_tooling = WordHelper.TableTooling(tableInfoDictAO[WordHelper.TableE.kToolEquip.value],
                                            WordHelper.TableE.kToolEquip)
    # table_tooling.printCells()
    resources = groupedData.resources
    table_tooling.addRows(resources.getAll())
    # for resource in resources.getAll():
    #     if isinstance(resource, TableData.ResourceRecord):
    #         table_tooling.addItem(resource.no, resource.name,
    #                               resource.spec1, resource.spec2, resource.spec3, resource.spec4)

    # 更改记录
    # table_revision = WordHelper.TableRevision(tableInfoDictAO[WordHelper.TableE.kRev.value], WordHelper.TableE.kRev)
    # # table_revision.printCells()
    # changes = groupedData.changes
    # for c in changes.getAll():
    #     if isinstance(c, TableData.RevisionRecord):
    #         table_revision.addItem(c.rev, c.date, groupedData.effectivity, c.change, c.source,
    #                                c.revised, c.approved, c.buyer)

    # 首页表
    table_model = WordHelper.TableModel(tableInfoDictAO[WordHelper.TableE.kModel.value], WordHelper.TableE.kModel)
    table_model.printCells()
    table_model.printMatrix()
    model = groupedData.model
    if isinstance(model, TableData.Model):
        table_model.setProgramNO(model.proNumber)
        table_model.setEff(groupedData.effectivity)
        table_model.setPartNum(model.partNumber)
        table_model.setInterchange(model.interchange)
        table_model.setModel(model.model)
        table_model.setCompiled(model.compiled)
        table_model.setCHECKEDBY(model.checked)
        table_model.setQA(model.qa)
        table_model.setAPPROVEDBY(model.appr)

        for i in model.getForOnePage():
            table_model.addItem(i.seq, i.no, i.sheet, i.eo1)

        ki = model.ki

        table_model.setSeal(ki)

    # 文档表
    table_stand_n_info = WordHelper.TableStandNInfo(tableInfoDictAO[WordHelper.TableE.kStandNInfo.value],
                                                    WordHelper.TableE.kStandNInfo)
    table_stand_n_info.printCells()
    documents = groupedData.document
    for d in documents.getProcessesAll():
        if isinstance(d, TableData.DocumentRecord):
            table_stand_n_info.addItem(d.no, d.name)

    table_stand_n_info.addRowsUnder(documents.getGeneralsAll())

    # 工程更改文件清单 暂时无用
    # table_catalog = WordHelper.TableCatalog(tableInfoDictAO[WordHelper.TableE.kCatalog.value], WordHelper.TableE.kCatalog)
    # table_catalog.printCells()
    # for i in range(1, 100):
    #     table_catalog.addItem(f"{i}", StringUtils.random_string(3), StringUtils.random_string(3), StringUtils.random_string(3), StringUtils.random_string(3),
    #                           StringUtils.random_string(3), StringUtils.random_string(3), StringUtils.random_string(3))

    # 保存修改后的文档
    doc.save(copied_file_path)
    print(f"文档已保存到: {copied_file_path}")
    return Path(copied_file_path)
    # os.startfile(copied_file_path)
